import 'package:cached_network_image/cached_network_image.dart';
import 'package:earclean/app/modules/widget/app_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/src/size_extension.dart';

import 'package:webview_flutter/webview_flutter.dart' as webv;
import 'package:webview_flutter/webview_flutter.dart';
import 'package:get/get.dart';

import '../controllers/message_controller.dart';

class MessageView extends GetView<MessageController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget(
          leadingCallback: () async {
            if (controller.webViewController != null) {
              bool a = await controller.webViewController!.canGoBack();
              if (a) {
                controller.webViewController!.goBack();
              } else {
                controller.webViewController!.reload();
              }
            }
          },
          titleStr: "消息"),
      body: web(),
    );
  }

  Set<JavascriptChannel> _loadJavascriptChannel() {
    final Set<JavascriptChannel> channels = Set<JavascriptChannel>();
    JavascriptChannel startFunction = JavascriptChannel(
        name: 'startFunction',
        onMessageReceived: (JavascriptMessage message) {
          // _getTitle();

          controller.messageHandle(message);
          // print(jsonDecode(message.message));
        });
    // JavascriptChannel h5JumpNative = JavascriptChannel(
    //     name: 'h5JumpNative',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });
    // JavascriptChannel appJump = JavascriptChannel(
    //     name: 'appJump',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });

    channels.addAll([
      startFunction,
    ]);
    return channels;
  }

  web() {
    return Obx(() => controller.chat_url.value.length > 0
        ? webv.WebView(
            initialUrl: controller.chat_url.value, //需要打开的url

            //是否支持js 默认是不支持的，
            javascriptMode: webv.JavascriptMode.unrestricted,
            gestureNavigationEnabled: true,
            //加载js方法到页面内，js通过此来调用flutter的方法
            javascriptChannels: _loadJavascriptChannel(),
            //路由委托（可以通过在此处拦截url实现JS调用Flutter部分）

            onWebViewCreated: (web) {
              controller.webViewController = web;
            },
            onProgress: (progress) async {
              print('object');
              print(progress);
              bool a = await controller.webViewController!.canGoBack();
              print(a);
            },
            onWebResourceError: (error) {
              print('加载失败');
              print(error);
            },

            onPageFinished: (url) async {
              String title = await controller.webViewController!
                  .runJavascriptReturningResult('document.title');
              print('title=======' + title);
              // controller.canGoBack.value =
              //     await controller.webViewController!.canGoBack();
              // // String currentUrl =
              //     await controller.webViewController!.currentUrl() ?? "";
              // controller.canGoBack.value = currentUrl == controller.url.value;
              // print('canGoBack=======' + controller.canGoBack.value.toString());
              // print('currentUrl=======' + currentUrl);

              // controller.title.value = title.length == 0 ? '直约' : title;
            },
          )
        : Container());
  }

  // Widget listWidget() {
  //   return ListView.separated(
  //       shrinkWrap: true,
  //       itemBuilder: (_, i) {
  //         Map item = controller.dataList[i];
  //         List infoL = item["info"];

  //         return InkWell(
  //           onTap: () {
  //             controller.toChat(item);
  //           },
  //           child: Container(
  //             padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
  //             child: Row(
  //               children: [
  //                 ClipOval(
  //                   child: LoadNetworkImageWidget(
  //                     width: 46.r,
  //                     height: 46.r,
  //                     fit: BoxFit.fill,
  //                     imageUrl: item['user_avatar'] ?? "",
  //                   ),
  //                 ),
  //                 SizedBox(
  //                   width: 10,
  //                 ),
  //                 Expanded(
  //                   child: Column(
  //                     children: [
  //                       Row(
  //                         children: [
  //                           Expanded(
  //                             child: Text(
  //                               item['user_name'] ?? "",
  //                               style: TextStyle(
  //                                   color: ColorConfig.body1_txt_color,
  //                                   fontSize: 14),
  //                             ),
  //                           ),
  //                           Text(
  //                             infoL.last['time'],
  //                             style: TextStyle(
  //                                 color: ColorConfig.subtitle_color,
  //                                 fontSize: 14),
  //                           ),
  //                         ],
  //                       ),
  //                       SizedBox(
  //                         height: 3,
  //                       ),
  //                       Container(
  //                         width: 1.sw,
  //                         child: Text(
  //                           infoL.last['msg'],
  //                           maxLines: 1,
  //                           overflow: TextOverflow.ellipsis,
  //                           style: TextStyle(
  //                               color: ColorConfig.subtitle_color,
  //                               fontSize: 14),
  //                         ),
  //                       ),
  //                     ],
  //                   ),
  //                 )
  //               ],
  //             ),
  //           ),
  //         );
  //       },
  //       separatorBuilder: (_, i) {
  //         return Container(
  //             margin: EdgeInsets.symmetric(horizontal: 12),
  //             width: 1.sw,
  //             height: 1,
  //             color: ColorConfig.diver_color);
  //       },
  //       itemCount: controller.dataList.length);
  // }

  // Widget noDataWidget() {
  //   return Container(
  //     width: 1.sw,
  //     child: Column(
  //       crossAxisAlignment: CrossAxisAlignment.center,
  //       children: [
  //         SizedBox(
  //           height: 128.h,
  //         ),
  //         Image.asset(
  //           'assets/images/pic@2x.png',
  //           width: 125.w,
  //           fit: BoxFit.cover,
  //         ),
  //         Text(
  //           '您没有收到消息哦～',
  //           style: TextStyle(fontSize: 12.sp, color: Color(0xFF606972)),
  //         ),
  //       ],
  //     ),
  //   );
  // }
}
